import {  Form, Input, message, Modal, Select, type FormProps } from "antd";
import { useEffect, useState } from "react";
import type {  AdministratorroleListFace } from "../../type/administratorrole";
import {  AdministratorroleroleList } from "../../apis/Administratorrole";
import type { addAdministratorParams, editFace } from "../../type/Administrator";
import { addAdministrator } from "../../apis/Administrator";

interface PropsParams {
    openAdd: boolean;
    refresh: () => void;
    editContent: editFace
}

type FieldType = {
    id?: number;
    name?: string;
    pass: string;
    passcheck: string;
    tel: string;
    username: string;
    typeid: number;
};
type optionsFace = {
    label: string;
    value: number;
}
export default function DiaLog({ openAdd, refresh, editContent }: PropsParams) {
    const [isModalOpen, setIsModalOpen] = useState(openAdd);
    const [form] = Form.useForm(); // 使用 Form.useForm 创建表单实例
    const [options, setOptions] = useState<optionsFace[]>([]);
    useEffect(() => {
        if (!isModalOpen) {
            refresh();
        }
    }, [isModalOpen]);
    useEffect(() => {
    if (editContent.id && Object.keys(editContent).length > 0) {
        // 使用 requestAnimationFrame 确保在下次重绘前执行
        requestAnimationFrame(() => {
            form.setFieldsValue({
                username: editContent.data?.name,
                pass: editContent.data?.pass,
                passcheck: editContent.data?.pass,
                name: editContent.data?.name,
                tel: editContent.data?.tel,
                typeid: editContent.data?.typeid,
                // 确保包含所有需要回显的字段
            });
        });
    } else if (!editContent.id) {
        // 添加模式下清空表单
        form.resetFields();
    }
}, [editContent.id, form]); // 依赖 editContent.id 而不是整个对象

    useEffect(() => {
        setIsModalOpen(openAdd);
    }, [openAdd]);

    const handleCancel = () => {
        refresh()
    };
    // 挂载后加载 下拉选择框的数据
    useEffect(()=>{
        GetList()
    },[])
    // 加载下拉选择的数据
    const GetList = async () => {
        const res = await AdministratorroleroleList();
        setOptions(res.data.list.map((item:AdministratorroleListFace)=>{ return { value: item.id, label: item.name }}))
    };
    const onFinish: FormProps<FieldType>['onFinish'] = async (values) => {
        editContent.id ? edit(values) : Add(values);
    };

    const edit = async (values: FieldType) => {
        const requestData = {
            ...values,
            id: editContent.id // 将 id 添加到请求数据中
        };
        let res = await addAdministrator(requestData as addAdministratorParams);
        if (res.errCode == 10000) {
            message.success('修改成功');
            refresh();
            form.resetFields(); // 使用 form 实例而不是 ref
        } else {
            message.error('修改失败');
        }
        setIsModalOpen(false);
    };

    const Add = async (values: FieldType) => {
        let res = await addAdministrator(values as addAdministratorParams);
        if (res.errCode == 10000) {
            message.success('添加成功');
            refresh();
            form.resetFields(); // 使用 form 实例而不是 ref
        } else {
            message.error('添加失败');
        }
        setIsModalOpen(false);
    };

    const handleOk = () => {
        form.submit(); // 使用 form 实例而不是 ref
    };
    // 下拉选择
    const onChange = (value: string) => {
        console.log(`selected ${value}`);
    };

    const onSearch = (value: string) => {
        console.log('search:', value);
    };
    return (
        <Modal
            title={editContent.id ? '修改管理员' : '添加管理员'}
            closable={{ 'aria-label': 'Custom Close Button' }}
            open={isModalOpen}
            onOk={handleOk}
            onCancel={handleCancel}
            okText="确认"
            cancelText="取消"
        >
            <Form
                form={form} // 绑定表单实例
                name="basic"
                labelCol={{ span: 8 }}
                wrapperCol={{ span: 16 }}
                style={{ maxWidth: 600 }}
                initialValues={{ remember: true }}
                onFinish={onFinish}
                autoComplete="off"
            >
                <Form.Item<FieldType>
                    label="账号"
                    name="username"
                    rules={[{ required: true, message: '请输入账号' }]}
                >
                    <Input />
                </Form.Item>
                <Form.Item<FieldType>
                    label="密码"
                    name="pass"
                    rules={[{ required: true, message: '请输入密码' }]}
                >
                    <Input />
                </Form.Item>
                <Form.Item<FieldType>
                    label="确认密码"
                    name="passcheck"
                    rules={[{ required: true, message: '请输入确认密码' }]}
                >
                    <Input />
                </Form.Item>
                <Form.Item<FieldType>
                    label="姓名"
                    name="name"
                    rules={[{ required: true, message: '请输入姓名' }]}
                >
                    <Input />
                </Form.Item>
                <Form.Item<FieldType>
                    label="联系方式"
                    name="tel"
                    rules={[{ required: true, message: '请输入联系方式' }]}
                >
                    <Input />
                </Form.Item>
                <Form.Item<FieldType>
                    label="角色"
                    name="typeid"
                    rules={[{ required: true, message: '请选择角色' }]}
                >
                    <Select
                        showSearch
                        placeholder="请选择角色"
                        optionFilterProp="label"
                        onChange={onChange}
                        onSearch={onSearch}
                        options={options}
                    />
                </Form.Item>
            </Form>
        </Modal>
    );
}